# -*- coding: utf-8 -*-
"""Item views."""
from flask import Blueprint, render_template, request, g, redirect, url_for, session, abort, jsonify, make_response
from flask.ext.login import LoginManager, login_required, login_user, logout_user, current_user
from flask_login import login_required
from sqlalchemy import and_
from AmoluoSale.item.models import Item, Order, Address, Admin, Reserve_Order
from AmoluoSale import utils
from AmoluoSale.extensions import db
import os,glob,json
import datetime as dt
from urllib import quote
import xmltodict
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
blueprint = Blueprint('item', __name__, static_folder='../static')

@blueprint.route('/item/pay', methods=['GET'])
def itemdetail():
    if request.method == 'GET':
        id = request.values.get('id', '')
        code = request.values.get('code')
        state = request.values.get('state')
        item = Item.query.get(id)
        picNum = utils.getPicNum(id)
        access_token = request.cookies.get('access_token')
        openid = request.cookies.get('openid')
        if code or state: # wx callback
            openid, access_token = utils.getToken(code)
            resp = make_response(render_template('items/item.html', item=item, picNum=picNum))
            if openid and access_token:
                resp.set_cookie('access_token', access_token)
                resp.set_cookie('openid', openid)
            return resp
        else: # normal call
            return render_template('items/item.html', item=item, picNum=picNum, isadmin=isAdmin(openid))

@blueprint.route('/validToken', methods=['POST'])
def validToken():
    access_token = request.values.get('access_token')
    openid = request.values.get('openid')
    if access_token and openid and utils.validToken(openid, access_token):
        return jsonify(data='suc')
    else:
        return jsonify(data='fail')

@blueprint.route('/itemlist/pay', methods=['GET'])
def goods():
    if request.method == 'GET':
        code = request.values.get('code')
        state = request.values.get('state')
        access_token = request.cookies.get('access_token')
        openid = request.cookies.get('openid')
        itemlist = Item.query.all()
        if code or state: # wx callback
            openid, access_token = utils.getToken(code)
            resp = make_response(render_template('items/itemlist.html',itemlist=itemlist, isadmin=isAdmin(openid)))
            if openid and access_token:
                resp.set_cookie('access_token', access_token)
                resp.set_cookie('openid', openid)
            return resp
        else: # normal call
            return render_template('items/itemlist.html',itemlist=itemlist, isadmin=isAdmin(openid))

@blueprint.route('/order', methods=['GET', 'POST'])
def order():
    wx_result ='''<xml>
                    <return_code><![CDATA[SUCCESS]]></return_code>
                    <return_msg><![CDATA[OK]]></return_msg>
                </xml>'''
    msg = xmltodict.parse(request.data)
    print msg
    if msg['xml']['return_code'] == 'SUCCESS':
        out_trade_no = msg['xml']['out_trade_no']
        transaction_id = msg['xml']['transaction_id']
        openid = msg['xml']['openid']
        order = Order.query.filter(and_(Order.out_trade_no == out_trade_no, Order.transaction_id == transaction_id)).first()
        addr = Address.query.filter(Address.openid == openid).order_by(Address.created_at.desc()).first()
        if order: # 已处理过
            print 'processed : %s'%order.as_dict()
            return wx_result
        else:
            order = Order()
            order.transaction_id = transaction_id
            order.out_trade_no = out_trade_no
            order.openid = openid
            attach = json.loads(msg['xml']['attach'])
            order.bank_type = msg['xml']['bank_type']
            order.cash_fee = int(msg['xml']['cash_fee'])
            order.fee_type = msg['xml']['fee_type']
            order.total_fee = int(msg['xml']['total_fee'])
            order.result_code = msg['xml']['result_code']
            openid = msg['xml']['openid']
            user = utils.getUserBySDK(openid)
            order.nickname = user.get('nickname')
            order.sex = user.get('sex')
            order.province = user.get('province')
            order.city = user.get('city')
            order.country = user.get('country')
            order.item_id = int(attach['item_id'])
            order.quantity = int(attach['quantity'])
            order.addr_id = addr.id
            db.session.add(order)
            item = Item.query.get(order.item_id)
            # should not update sold number here, but in celery
            # item.sold += order.quantity
            db.session.commit()
            data = {
                "first":{"value":"您好，欢迎使用多宝汇抢购平台。"},
                "keyword1":{"value":item.title},
                "keyword2":{"value":'%.2f'%item.now_price+"元"},
                "keyword3":{"value":str(order.quantity)+"件"},
                "keyword4":{"value":order.created_at.strftime('%Y-%m-%d %H:%M:%S')},
                "remark":{"value":"祝您生活愉快！"}
            }
            utils.sendBuyNotify(openid, data)
            return wx_result



@blueprint.route('/orderList', methods=['GET','POST'])
def orderList():
    if request.method == 'POST':
        status = int(request.values.get('status',1))
        orderList = []
        if status == 1:
            orderList = Order.query.filter(Order.status == int(status)).order_by(Order.created_at.desc())
        elif status == 2:
            orderList = Order.query.filter(Order.status == int(status)).order_by(Order.delivered_at.desc())
        orderEntityList = []
        for order in orderList:
            orderEntity = {}
            item = Item.query.get(order.item_id)
            addr = Address.query.get(order.addr_id)
            orderEntity.update(item.as_dict())
            orderEntity.update(addr.as_dict())
            orderEntity.update(order.as_dict())
            orderEntity['created_at'] = orderEntity['created_at'].strftime('%Y-%m-%d %H:%M:%S')
            if orderEntity['delivered_at']:
                orderEntity['delivered_at'] = orderEntity['delivered_at'].strftime('%Y-%m-%d %H:%M:%S')
            orderEntityList.append(orderEntity)
        return jsonify(data=orderEntityList)
    else:
        return render_template('items/orderlist.html', isadmin=True)

@blueprint.route('/myOrders', methods=['GET','POST'])
def myOrders():
    if request.method == 'POST':
        openid = request.cookies.get('openid')
        orderList = Order.query.filter(Order.openid == openid).order_by(Order.created_at.desc())
        roList = Reserve_Order.query.filter(Reserve_Order.openid == openid).order_by(Reserve_Order.created_at.desc())
        orderEntityList = []

        for ro in roList:
            orderEntity = {}
            item = Item.query.get(ro.item_id)
            orderEntity.update(item.as_dict())
            orderEntity.update(ro.as_dict())
            orderEntity['created_at'] = orderEntity['created_at'].strftime('%Y-%m-%d %H:%M:%S')
            orderEntity['status'] = 3 if dt.datetime.now() < ro.expire_at else 4
            orderEntityList.append(orderEntity)
        for order in orderList:
            orderEntity = {}
            item = Item.query.get(order.item_id)
            orderEntity.update(item.as_dict())
            orderEntity.update(order.as_dict())
            orderEntity['created_at'] = orderEntity['created_at'].strftime('%Y-%m-%d %H:%M:%S')
            orderEntityList.append(orderEntity)
        return jsonify(data=orderEntityList)
    else:
        code = request.values.get('code')
        state = request.values.get('state')
        access_token = request.cookies.get('access_token')
        openid = request.cookies.get('openid')
        if code or state: # wx callback
            openid, access_token = utils.getToken(code)
            resp = make_response(render_template('items/myOrders.html'))
            if openid and access_token:
                resp.set_cookie('access_token', access_token)
                resp.set_cookie('openid', openid)
            return resp
        else:
            return render_template('items/myOrders.html', isadmin=isAdmin(openid))


@blueprint.route('/addr', methods=['GET','POST'])
def addr():
    roid = request.values.get('roid', '')
    id = request.values.get('id', '')
    quantity = request.values.get('quantity', '')
    task_id = request.values.get('task_id', '')
    url = 'http://flashsales.tangle-up.top/addr/get'
    url += '?id='+id
    url += '&roid='+roid
    url += '&quantity='+quantity
    url += '&task_id='+task_id
    url = quote(url)
    redirectUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5bf47679c84ef3c8&redirect_uri='+url+'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
    return redirect(redirectUrl)


@blueprint.route('/addr/get', methods=['GET','POST'])
def getaddr():
    roid = request.values.get('roid', '')
    id = request.values.get('id', '')
    quantity = request.values.get('quantity', '')
    task_id = request.values.get('task_id', '')
    code = request.values.get('code')
    state = request.values.get('state')
    openid, access_token = utils.getToken(code)
    addr = None
    ro = None
    if id != '':
        item = Item.query.get(id)
    if roid != '':
        ro = Reserve_Order.query.get(int(roid))
        item = Item.query.get(ro.item_id)
        if ro.addr_id:
            addr = Address.query.get(ro.addr_id)
    money = item.now_price * int(quantity)
    expire = ro.expire_at if ro else None
    resp = make_response(render_template('items/addr.html', item=item, quantity=quantity, money=money, addr=addr, expire = expire))
    resp.set_cookie('access_token', access_token)
    resp.set_cookie('openid', openid)
    resp.set_cookie('code', code)
    resp.set_cookie('state', state)
    resp.set_cookie('task_id', task_id)
    return resp

@blueprint.route("/jsapi/pay", methods=['GET','POST'])
def jsapi_pay():
    quantity = int(request.values.get('quantity', '0'))
    access_token = request.cookies.get('access_token')
    item_id = request.values.get('itemid', '')
    openid = request.cookies.get('openid')
    addr = Address()
    addr.openid = openid
    addr.proviceFirstStageName = request.values.get('proviceFirstStageName')
    addr.addressCitySecondStageName = request.values.get('addressCitySecondStageName')
    addr.addressCountiesThirdStageName = request.values.get('addressCountiesThirdStageName')
    addr.addressDetailInfo = request.values.get('addressDetailInfo')
    addr.telNumber = request.values.get('telNumber')
    addr.userName = request.values.get('userName')
    addr.addressPostalCode = request.values.get('addressPostalCode')
    db.session.add(addr)
    db.session.commit()
    # ro = Reserve_Order.query.filter(Reserve_Order.openid == openid)
    # ro.addr_id = addr.id
    # db.session.commit()
    attach = {'quantity':quantity, 'item_id':item_id}
    item = Item.query.get(item_id)
    params = utils.createOrder(item.title, int(item.now_price*quantity*100), openid, url_for('.order'), json.dumps(attach))
    return jsonify(params = params)

@blueprint.route("/getJSTicket", methods=['GET','POST'])
def getJSTicket():
    return utils.getJSTicket()


@blueprint.route("/deliver", methods=['GET','POST'])
def deliver():
    express_no = request.values.get('express_no')
    express_com = request.values.get('express_com')
    id = request.values.get('id')
    order = Order.query.get(id)
    order.express_no = express_no
    order.express_company = express_com
    order.delivered_at = dt.datetime.now()
    order.status = 2
    db.session.commit()
    item = Item.query.get(order.item_id)
    data = {
        "first":{"value":"您好，你的商品已发货。"},
        "keyword1":{"value":express_com},
        "keyword2":{"value":express_no},
        "keyword3":{"value":item.title},
        "keyword4":{"value":order.quantity},
        "remark":{"value":"请注意查收。"}
    }
    utils.sendDeliverNotify(order.openid, data)
    return jsonify(data='suc')

@blueprint.route("/unpaidOrder", methods=['GET','POST'])
def unpaidOrder():
    roid = request.values.get('roid', '')
    ro = Reserve_Order.query.filter_by(int(roid))


def isAdmin(openid):
    count = Admin.query.filter(Admin.openid == openid).count()
    return count == 1




